package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Chen
 * app端登录操作
 */
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserLoginService {

    /**
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //判断dto  dto.getEquipmentId()==null ||
        if( StringUtils.isEmpty(dto.getPhone())|| StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或者密码不能为空");
        }

        //判断当前手机号是否存在
        LambdaQueryWrapper<ApUser> queryWrapper= Wrappers.lambdaQuery();
        queryWrapper.eq(ApUser::getPhone,dto.getPhone());
        ApUser apUser = getOne(queryWrapper);
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //校验密码是否一致
        //明文+盐
        String pswd=dto.getPassword()+apUser.getSalt();
        //对明文进行加密设置
        String pwd = DigestUtils.md5DigestAsHex(pswd.getBytes());

        //4.校验密码是否一致
        if((apUser.getPassword()).equals(pwd)){
            //4.1 如果一致，生成token
            String token = AppJwtUtil.getToken(Long.parseLong(apUser.getId() + ""));

            Map<String,Object> map=new HashMap<>(16);
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码不一致");
    }
}
